'use client';

import React, { useState, useEffect } from 'react';
import { Card, Form, DatePicker, TimePicker, Select, Button, message, Row, Col, Table, Tag, Typography, Space, Modal } from 'antd';
import { setCheckInTime, getCheckInTime, getAllCheckInTime, CheckInTimeData } from '@/lib/attendance';
import { getAllDepartments } from '@/lib/departments';
import { getAcademies } from '@/lib/academy';
import { getOtherDepts } from '@/lib/otherdept';
import Layout from '@/components/Layout';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { PlusOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Title } = Typography;

interface FormValues {
  dateRange: [Dayjs, Dayjs];
  startTime: Dayjs;
  endTime: Dayjs;
  deptId: number;
  deptType: number;
}

interface Department {
  deptId: number;
  deptName: string;
}

interface Academy {
  academyId: number;
  academyName: string;
}

interface OtherDepartment {
  otherDeptId: number;
  otherDeptName: string;
}

const SetCheckInTime: React.FC = () => {
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [currentSettings, setCurrentSettings] = useState<any>(null);
  const [departments, setDepartments] = useState<Department[]>([]);
  const [academies, setAcademies] = useState<Academy[]>([]);
  const [otherDepts, setOtherDepts] = useState<OtherDepartment[]>([]);
  const [selectedDeptType, setSelectedDeptType] = useState<number>();

  // 打卡设置列表相关状态
  const [checkInSettings, setCheckInSettings] = useState<CheckInTimeData[]>([]);
  const [checkInTotal, setCheckInTotal] = useState(0);
  const [checkInLoading, setCheckInLoading] = useState(false);
  const [queryParams, setQueryParams] = useState({
    page: 1,
    pageSize: 10,
    deptType: undefined as number | undefined,
  });

  // 加载所有类型的部门数据
  useEffect(() => {
    const loadDepartments = async () => {
      try {
        const [deptRes, academyRes, otherDeptRes] = await Promise.all([
          getAllDepartments(),
          getAcademies(),
          getOtherDepts()
        ]);

        console.log('【部门数据】职能部门:', deptRes.data);
        console.log('【部门数据】二级学院:', academyRes.data);
        console.log('【部门数据】其他部门:', otherDeptRes.data);

        if (deptRes.data.code === 1) {
          setDepartments(deptRes.data.data || []);
        }
        if (academyRes.data.code === 1) {
          setAcademies(academyRes.data.data || []);
        }
        if (otherDeptRes.data.code === 1) {
          setOtherDepts(otherDeptRes.data.data || []);
        }
      } catch (error) {
        console.error('获取部门数据失败:', error);
        message.error('获取部门数据失败');
      }
    };

    loadDepartments();
  }, []);

  // 加载当前设置
  const loadCurrentSettings = async (deptId: number, deptType: number) => {
    try {
      const params = { deptId, deptType };
      console.log('【获取考勤设置】请求参数:', params);
      
      const response = await getCheckInTime(params);
      console.log('【获取考勤设置】响应数据:', response.data);

      if (response.data.code === 1) {
        const settings = response.data.data;
        setCurrentSettings(settings);
        
        // 更新表单值
        form.setFieldsValue({
          deptId: settings.setDeptId,
          deptType: settings.setDeptType,
          dateRange: [
            dayjs(settings.setStartDate),
            dayjs(settings.setEndDate)
          ],
          startTime: dayjs(settings.setStartTime, 'HH:mm:ss'),
          endTime: dayjs(settings.setEndTime, 'HH:mm:ss')
        });
      }
    } catch (error) {
      console.error('获取考勤设置失败:', error);
      message.error('获取考勤设置失败');
    }
  };

  // 处理部门类型变化
  const handleDeptTypeChange = (value: number) => {
    setSelectedDeptType(value);
    form.setFieldValue('deptId', undefined);
  };

  // 当部门和部门类型都选择后，获取当前设置
  const handleDeptChange = async () => {
    const values = form.getFieldsValue();
    if (values.deptId && values.deptType) {
      await loadCurrentSettings(values.deptId, values.deptType);
    }
  };

  // 打开模态框
  const showModal = () => {
    form.resetFields();
    setIsModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    form.resetFields();
    setCurrentSettings(null);
    setSelectedDeptType(undefined);
    setIsModalVisible(false);
  };

  const onFinish = async (values: FormValues) => {
    setIsLoading(true);
    try {
      const settings = {
        setDeptId: values.deptId,
        setDeptType: values.deptType,
        setStartDate: values.dateRange[0].format('YYYY-MM-DD'),
        setEndDate: values.dateRange[1].format('YYYY-MM-DD'),
        setStartTime: values.startTime.format('HH:mm:ss'),
        setEndTime: values.endTime.format('HH:mm:ss')
      };

      console.log('【设置考勤时间】请求参数:', settings);
      const response = await setCheckInTime(settings);
      console.log('【设置考勤时间】响应结果:', response.data);

      if (response.data.code === 1) {
        message.success('打卡时间设置成功');
        handleCancel(); // 关闭模态框
        fetchCheckInSettings(); // 刷新列表
      } else {
        message.error('打卡时间设置失败: ' + response.data.msg);
      }
    } catch (error: any) {
      console.error('设置考勤时间失败:', error);
      message.error('请求失败: ' + (error.message || '未知错误'));
    } finally {
      setIsLoading(false);
    }
  };

  // 根据选择的部门类型返回对应的部门选项
  const getDepartmentOptions = () => {
    switch (selectedDeptType) {
      case 1:
        return departments.map(dept => (
          <Option key={dept.deptId} value={dept.deptId}>
            {dept.deptName}
          </Option>
        ));
      case 2:
        return academies.map(academy => (
          <Option key={academy.academyId} value={academy.academyId}>
            {academy.academyName}
          </Option>
        ));
      case 3:
        return otherDepts.map(dept => (
          <Option key={dept.otherDeptId} value={dept.otherDeptId}>
            {dept.otherDeptName}
          </Option>
        ));
      default:
        return [];
    }
  };

  // 获取打卡设置列表
  const fetchCheckInSettings = async () => {
    setCheckInLoading(true);
    try {
      const response = await getAllCheckInTime(queryParams);
      console.log('【获取打卡设置列表】响应数据:', response.data);
      if (response.data.code === 1) {
        setCheckInSettings(response.data.data.row);
        setCheckInTotal(response.data.data.total);
      } else {
        message.error('获取打卡设置列表失败：' + response.data.msg);
      }
    } catch (error) {
      console.error('获取打卡设置列表失败:', error);
      message.error('获取打卡设置列表失败');
    } finally {
      setCheckInLoading(false);
    }
  };

  // 当查询参数变化时重新获取数据
  useEffect(() => {
    fetchCheckInSettings();
  }, [queryParams]);

  // 打卡设置表格列定义
  const columns = [
    {
      title: '部门类型',
      dataIndex: 'setDeptType',
      key: 'setDeptType',
      width: 180,
      render: (type: number) => {
        const types = {
          1: { text: '职能部门', color: 'blue' },
          2: { text: '二级学院', color: 'green' },
          3: { text: '其他部门', color: 'orange' }
        };
        const { text, color } = types[type as keyof typeof types] || { text: '未知', color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '部门ID',
      dataIndex: 'setDeptId',
      key: 'setDeptId',
      width: 100,
      align: 'center' as const
    },
    {
      title: '打卡日期范围',
      key: 'dateRange',
      render: (_: any, record: CheckInTimeData) => {
        const startDate = dayjs(record.setStartDate).format('YYYY-MM-DD');
        const endDate = dayjs(record.setEndDate).format('YYYY-MM-DD');
        return (
          <span style={{ color: '#1890ff' }}>
            {startDate} 至 {endDate}
          </span>
        );
      }
    },
    {
      title: '打卡时间',
      key: 'timeRange',
      width: 200,
      render: (_: any, record: CheckInTimeData) => (
        <Tag color="processing">
          {record.setStartTime} - {record.setEndTime}
        </Tag>
      )
    }
  ];

  return (
    <Layout>
      {/* 打卡设置列表卡片 */}
      <Card style={{ margin: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
          <Title level={4} style={{ marginBottom: 0 }}>打卡设置列表</Title>
          <Space>
            <Select
              placeholder="按部门类型筛选"
              style={{ width: 200 }}
              allowClear
              value={queryParams.deptType}
              onChange={(value) => setQueryParams(prev => ({ ...prev, deptType: value, page: 1 }))}
            >
              <Option value={1}>职能部门</Option>
              <Option value={2}>二级学院</Option>
              <Option value={3}>其他部门（教辅单位）</Option>
            </Select>
            <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
              设置打卡时间
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={checkInSettings}
          rowKey="id"
          loading={checkInLoading}
          pagination={{
            current: queryParams.page,
            pageSize: queryParams.pageSize,
            total: checkInTotal,
            onChange: (page, pageSize) => setQueryParams(prev => ({ ...prev, page, pageSize })),
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
            showQuickJumper: true
          }}
          bordered
          size="middle"
        />
      </Card>

      {/* 设置打卡时间模态框 */}
      <Modal
        title="设置打卡时间"
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        maskClosable={false}
        width={600}
      >
        <Form form={form} onFinish={onFinish} layout="vertical">
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="deptType"
                label="部门类型"
                rules={[{ required: true, message: '请选择部门类型' }]}
              >
                <Select 
                  placeholder="请选择部门类型"
                  onChange={handleDeptTypeChange}
                >
                  <Option value={1}>职能部门</Option>
                  <Option value={2}>二级学院</Option>
                  <Option value={3}>其他部门（教辅单位）</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="deptId"
                label="部门"
                rules={[{ required: true, message: '请选择部门' }]}
              >
                <Select 
                  placeholder="请选择部门"
                  onChange={handleDeptChange}
                  disabled={!selectedDeptType}
                >
                  {getDepartmentOptions()}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="dateRange"
            label="打卡日期范围"
            rules={[{ required: true, message: '请选择打卡日期范围' }]}
          >
            <RangePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
          </Form.Item>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="startTime"
                label="上班打卡时间"
                rules={[{ required: true, message: '请选择上班打卡时间' }]}
              >
                <TimePicker style={{ width: '100%' }} format="HH:mm:ss" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="endTime"
                label="下班打卡时间"
                rules={[{ required: true, message: '请选择下班打卡时间' }]}
              >
                <TimePicker style={{ width: '100%' }} format="HH:mm:ss" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={handleCancel}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={isLoading}>
                {isLoading ? '提交中...' : '确定'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default SetCheckInTime;